<!DOCTYPE html>
<meta charset="utf-8">
<title>Setting style.cssText keeps only valid properties</title>
<link rel="help" href="https://drafts.csswg.org/cssom/#cssstyledeclaration">
<link rel="help" href="https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-csstext">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<!-- regression test for https://github.com/jsdom/cssstyle/pull/249 -->

<style>
.div {
  color: red;
}
</style>
<div id="div" class="div"></div>
<script>
"use strict";

const cssRule = document.styleSheets[0].cssRules[0];

test(() => {
  assert_equals(cssRule.style.cssText, "color: red;");
}, "initial value of cssRule.style.cssText");

test(() => {
  cssRule.style.cssText = "color: green!";
  assert_equals(cssRule.style.cssText, "");
}, "sets empty string for invalid cssText");

test(() => {
  // valid property followed by invalid property followed by valid property
  cssRule.style.cssText = "color: green; color: invalid!; background: blue;";
  // ignores invalid properties
  assert_equals(cssRule.style.cssText, "color: green; background: blue;");

  // only valid properties
  cssRule.style.cssText = "color: olivedrab; color: peru; background: bisque;";
  // keeps the last one of the same property
  assert_equals(cssRule.style.cssText, "color: peru; background: bisque;");

  // valid property followed by a nested selector rule
  cssRule.style.cssText = "color: olivedrab; &.d { color: peru; }";
  // ignores the nested selector rule
  assert_equals(cssRule.style.cssText, "color: olivedrab;");

  // valid property followed by a nested selector rule followed by two valid properties and an invalid property
  cssRule.style.cssText = "color: olivedrab; &.d { color: peru; } color: green; background: red; invalid: rule;";
  // ignores the property immediately after the nested rule
  assert_equals(cssRule.style.cssText, "color: olivedrab; background: red;");

  // valid property followed by a at-rule followed by a valid property
  cssRule.style.cssText = "color: blue; @media screen { color: red; } color: orange;";
  // includes the the property immediately after an at-rule
  assert_equals(cssRule.style.cssText, "color: orange;");

  // valid property followed by a nested rule, two at-rules and two valid properties
  cssRule.style.cssText = `
    color: blue;
    &.d { color: peru; }
    @media screen { color: red; }
    @layer { color: black; }
    color: pink;
    background: orange;`;
  // ignores the first property found after the nested selector rule along with the at-rules
  assert_equals(cssRule.style.cssText, "color: blue; background: orange;");
}, "sets only the valid properties for partially valid cssText");
</script>
